package org.gradle.j2ssh.test;


import java.security.MessageDigest;
import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



public class ItmpCipher {
	private static String key="uM1esccCq*Eshore";
	private static Logger logger=LoggerFactory.getLogger(ItmpCipher.class);
	private static String patternStr="[^0-9a-fA-F]";
	private static String KEY_TYPE="AES";
	private static String CIPHER_TYPE="AES/ECB/PKCS5Padding";
	private static Pattern pat=Pattern.compile(patternStr);
	
	public static String NAME_NEED_CRYPT=";password;community;";
	
	
	public static boolean isPassword(String paramName){
		return paramName!=null&&NAME_NEED_CRYPT.indexOf(";"+paramName.toLowerCase()+";")>=0;
	}
	
	public static boolean isEncrypted(String paramValue){
		if(paramValue==null||"".equals(paramValue)){
			return false;
		}
		return (paramValue.length()%32==0&&!pat.matcher(paramValue).find());

	}


	public static String doEncrypt(String s){
		if(s!=null&&s.length()!=0&&s.length()%32==0&&!pat.matcher(s).find()){
			logger.warn("请检查待加密字符串[{}]格式",s);
		}
		String realKey=ItmpCipher.encryptToMD5(key);
		SecretKeySpec sks=new SecretKeySpec(ItmpCipher.hex2byte(realKey),KEY_TYPE);
		return ItmpCipher.encrypt(sks, s);
	}
	

	

	public static String doDecrypt(String password){
		if(password==null||password.length()==0){
			logger.error("待解密字符串为空");
			return password;
		}
		if(password.length()%32!=0||pat.matcher(password).find()){
			//当密码明显是没经过加密是，不用解密，直接返回该密码
			logger.debug("待解密字符串[{}]格式错误，不执行解密，直接返回",password);
			return password;
		}else{
			String realKey=ItmpCipher.encryptToMD5(key);
			SecretKeySpec sks=new SecretKeySpec(ItmpCipher.hex2byte(realKey),KEY_TYPE);
			return ItmpCipher.decrypt(sks, password);
		}
	}
	
	
	
	/**
	 * 生成MD5摘要
	 */
	public static String encryptToMD5(String info) {
		return messageDigest("MD5",info);
	}

	/**
	 * 生成SHA摘要
	 */
	public static String encryptToSHA(String info) {
		return messageDigest("SHA-512",info);
	}
	
	private static String messageDigest(String algorithm,String info){
		try {
			MessageDigest alga = MessageDigest.getInstance(algorithm);
			// 添加要进行计算摘要的信息
			alga.update(info.getBytes("UTF-8"));
			// 得到该摘要,并将其转换为字符串
			return byte2hex(alga.digest());
		} catch (Exception e) {
			logger.error("生成摘要出错，算法："+algorithm,e);
			return null;
		}

		
	}
	


	/**
	 * 根据密匙进行DES加密
	 * 
	 * @param key
	 *            密匙
	 * @param info
	 *            要加密的信息
	 * @return String 加密后的信息
	 */
	private  static String encrypt(SecretKey key, String info) {
		info=info==null?"":info;
		// 定义 加密算法,可用 DES,DESede,Blowfish
		//String Algorithm = key.getAlgorithm();
		// 加密随机数生成器 (RNG),(可以不写)
		//SecureRandom sr = new SecureRandom();
		// 定义要生成的密文
		byte[] cipherByte = null;
		try {
			// 得到加密/解密器
			Cipher c1 = Cipher.getInstance(CIPHER_TYPE);
			// 用指定的密钥和模式初始化Cipher对象
			// 参数:(ENCRYPT_MODE, DECRYPT_MODE, WRAP_MODE,UNWRAP_MODE)

			c1.init(Cipher.ENCRYPT_MODE, key);
			// 对要加密的内容进行编码处理,
			cipherByte = c1.doFinal(info.getBytes("UTF-8"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 返回密文的十六进制形式
		return byte2hex(cipherByte);
	}

	/**
	 * 根据密匙进行DES或AES解密
	 * @param key	密匙
	 * @param sInfo	要解密的密文
	 * @return String 返回解密后信息
	 */
	private static String decrypt(SecretKey key, String sInfo) {
		// 定义 加密算法,
		//String Algorithm =key.getAlgorithm();
		// 加密随机数生成器 (RNG)
		//SecureRandom sr = new SecureRandom();
		byte[] cipherByte = null;
		try {
			// 得到加密/解密器
			Cipher c1 = Cipher.getInstance(CIPHER_TYPE);
			//c1.getBlockSize();
			// 用指定的密钥和模式初始化Cipher对象
			c1.init(Cipher.DECRYPT_MODE, key);
			// 对要解密的内容进行编码处理
			cipherByte = c1.doFinal(hex2byte(sInfo));
		} catch (Exception e) {
			e.printStackTrace();
		}
		// return byte2hex(cipherByte);
		return new String(cipherByte);
	}



	
	/**
	 * 将二进制转化为16进制字符串
	 */
	public static String byte2hex(byte[] b) {
		
		StringBuilder bder=new StringBuilder();
		String stmp = null;
		for (int n = 0; n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0XFF);
			if (stmp.length() == 1) {
				bder.append("0");
			} 
			bder.append(stmp);
			
		}
		return bder.toString().toUpperCase();
	}

	/**
	 * 十六进制字符串转化为byte数组
	 */
	private  static byte[] hex2byte(String hex) {
		if(hex.length()%2!=0){
			throw new IllegalArgumentException("参数长度不合法");
		}
		byte[] result=new byte[hex.length()/2];
		for(int i=0;i<result.length;i++){
			result[i]=uniteBytes(hex.charAt(i*2),hex.charAt(i*2+1));
		}
		return result;
	}
	
	
	

	/**
	 * 将两个ASCII字符合成一个字节； 如："EF"--> 0xEF
	 * @param c1   
	 * @param c2
	 * @return byte
	 */
	private static byte uniteBytes(char c1, char c2) {
		byte _b0 = Byte.decode("0x" + c1);
		_b0 = (byte) (_b0 << 4);
		byte _b1 = Byte.decode("0x" + c2);
		return (byte) (_b0 ^ _b1);
	}


	public static void main(String[] args) {
		System.out.println(ItmpCipher.doDecrypt("0DFFDF8E0F1B737F352C6819FA2855E2"));
		
	}

	
	

}
